﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using DevComponents.WpfDock;
using DevComponents.WpfRibbon;
using DiscoveryLogic.Analytics.BusinessLogic;
using DiscoveryLogic.Analytics.BusinessLogic.Clusters;
using DiscoveryLogic.Analytics.BusinessLogic.Entities;
using DiscoveryLogic.Analytics.BusinessLogic.Exports;
using DiscoveryLogic.Analytics.BusinessLogic.Measures;
using DiscoveryLogic.Analytics.BusinessLogic.Networks;
using DiscoveryLogic.Analytics.BusinessLogic.Rules;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.DataObjects.Networks;
using DiscoveryLogic.Analytics.DataObjects.Rules;
using DiscoveryLogic.Analytics.DataObjects.Visuals;
using DiscoveryLogic.Analytics.Modules;
using DiscoveryLogic.Analytics.Modules.DataImport;
using DiscoveryLogic.Analytics.Modules.Diagrams.NetworkDiagrams;
using DiscoveryLogic.Analytics.Modules.Editors;
using DiscoveryLogic.Analytics.Modules.Entities;
using DiscoveryLogic.Analytics.Modules.ERRules;
using DiscoveryLogic.Analytics.Modules.ImportRules;
using DiscoveryLogic.Analytics.Modules.Networks;
using DiscoveryLogic.Analytics.Modules.Searches;
using DiscoveryLogic.Analytics.Modules.Tools;
using DiscoveryLogic.Analytics.UI.Common;
using DiscoveryLogic.Analytics.UI.Common.Commands;
using DiscoveryLogic.Analytics.UI.Common.Wizard;
using DiscoveryLogic.Common.Utilities;
using Microsoft.Practices.Composite.Events;
using EntityBase=DiscoveryLogic.Analytics.DataObjects.EntityBase;

namespace DiscoveryLogic.Analytics.Studio
{
	/// <summary>
	/// Interaction logic for VisualStudioLikeShell.xaml
	/// </summary>
	public partial class VisualStudioLikeShell : RibbonWindow
	{
	    private Label lblSearchField = null;
	    private TextBox txtSearch = null;

		#region init
		public VisualStudioLikeShell()
		{
			InitializeComponent();

			this.InitCommands();
		}

		private void InitCommands()
		{
			RibbonCommandManager.Connect(ApplicationCommands.Open, new ButtonDropDownCommandExtender("Open", "/images/FolderOpen32.png"));
			RibbonCommandManager.Connect(ApplicationCommands.New, new ButtonDropDownCommandExtender("New", "/images/Document32.png", "/images/NewDocument.png"));
			RibbonCommandManager.Connect(ApplicationCommands.Close, new ButtonDropDownCommandExtender("Exit RibbonPad", "/images/Exit.png"));
			RibbonCommandManager.Connect(ApplicationCommands.Paste, new ButtonDropDownCommandExtender("Paste", "/images/Paste32.png", "/images/Paste16.png"));
			RibbonCommandManager.Connect(ApplicationCommands.Cut, new ButtonDropDownCommandExtender("Cut", "/images/Cut.png"));
			RibbonCommandManager.Connect(ApplicationCommands.Copy, new ButtonDropDownCommandExtender("Copy", "/images/Copy.png"));
			RibbonCommandManager.Connect(ApplicationCommands.Save, new ButtonDropDownCommandExtender("Save", "/images/Save32.png", "/images/Save.png"));
			RibbonCommandManager.Connect(ApplicationCommands.SaveAs, new ButtonDropDownCommandExtender("Save As...", "/images/SaveAs32.png"));
			RibbonCommandManager.Connect(ApplicationCommands.Print, new ButtonDropDownCommandExtender("Print...", "/images/Print32.png"));
            // RibbonCommandManager.Connect(WindowCommands.QuickSearchCommand, new ButtonDropDownCommandExtender("Search...", "images/find.ico"));

			// Create command bindings for some commands
			this.CommandBindings.Add(new CommandBinding(WindowCommands.MostRecentlyUsed, MostRecentlyUsedCommandExecute));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.CloseDocument, CloseDocumentCommandExecute));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.Options, CloseDocumentCommandExecute));
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, CloseCommandExecute));
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, AppCommandExecute));
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.New, AppCommandExecute));
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, AppCommandExecute));
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.SaveAs, AppCommandExecute));
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Print, AppCommandExecute));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.BlueTheme, ChangeRibbonColor, CanExecuteChangeRibbonColor));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.BlackTheme, ChangeRibbonColor, CanExecuteChangeRibbonColor));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.SilverTheme, ChangeRibbonColor, CanExecuteChangeRibbonColor));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.OrangeTheme, ChangeRibbonColor, CanExecuteChangeRibbonColor));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.MagentaTheme, ChangeRibbonColor, CanExecuteChangeRibbonColor));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.GreenTheme, ChangeRibbonColor, CanExecuteChangeRibbonColor));
			this.CommandBindings.Add(new CommandBinding(WindowCommands.DarkBlueTheme, ChangeRibbonColor, CanExecuteChangeRibbonColor));
            
            
		}

	    private void WindowLoaded(object sender, RoutedEventArgs e)
		{
			this.LoadModules();
            this.InitRibbonTabs();
            this.InitStatusBar();
	        this.LoadUserGuide();
		}

		private void LoadModules()
		{
			//Toolbox toolbox = new Toolbox();
			//this.dockTools.Content = toolbox;

            //EntityRelationshipRuleEditor ruleEditor=new EntityRelationshipRuleEditor();
            //this.tabGraph.Content = ruleEditor;

            //EntitySetsTreeView entityTrees = new EntitySetsTreeView();
            //this.tabGraph.Content = entityTrees;
		}

        private Image LoadImage(string imagePath, double size)
        {
            Image image = new Image();
            image.Stretch = Stretch.Fill;
            image.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
            image.SetValue(Image.WidthProperty, size);
            image.SetValue(Image.HeightProperty, size);
            return image;
        }

        private void LoadUserGuide()
        {
            Uri fileUri=new Uri("User Guide.rtf",UriKind.Relative);
            StreamReader reader = new StreamReader(Application.GetContentStream(fileUri).Stream);
            string content = reader.ReadToEnd();
            reader.Close();
            this.docReader.DisplayContent(content);
        }
		#endregion

        #region ribbon tab
        private void InitRibbonTabs()
        {
            this.InitDataRibbonTab(this.rtData);
            this.InitRelationRibbonTab(this.rtRelations);
            this.InitAnalysisRibbonTab(this.rtAnalysis);
            this.InitReportRibbonTab(this.rtReports);
        }

        private void InitDataRibbonTab(RibbonTab dataTab)
        {
            RibbonBarPanel panelData = new RibbonBarPanel();
            panelData.Height = 89;
            dataTab.Content = panelData;
            RibbonBar bar;
            ButtonDropDown button;

            // import data 
            bar = new RibbonBar();
            bar.Header = "Import Data";
            panelData.Children.Add(bar);
            
            button = new ButtonDropDown();
            button.Header = "Grants";
            button.Image = LoadImage("images/"+EntityIcons.ImportGrantIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(this.ImportData);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Organizations";
            button.Image = LoadImage("images/"+EntityIcons.ImportOrgIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(this.ImportData);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Publications";
            button.Image = LoadImage("images/"+EntityIcons.ImportPubIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(this.ImportData);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Persons";
            button.Image = LoadImage("images/" + EntityIcons.ImportPersonIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(this.ImportData);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Excel data";
            button.Image = LoadImage("images/excel.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(this.ImportExcelData);
            bar.Items.Add(button);

            //// open data 
            //bar = new RibbonBar();
            //bar.Header = "Open Data";
            //panelData.Children.Add(bar);

            //button = new ButtonDropDown();
            //button.Header = "Grants";
            //button.Image = LoadImage("images/Paste32.png", 32);
            //button.ImageSmall = LoadImage("images/Paste16.png", 16);
            //button.ImagePosition = eButtonImagePosition.Top;
            //bar.Items.Add(button);

            //button = new ButtonDropDown();
            //button.Header = "Organizations";
            //button.Image = LoadImage("images/Cut.png", 16);
            //bar.Items.Add(button);

            //button = new ButtonDropDown();
            //button.Header = "Publications";
            //button.Image = LoadImage("images/Copy.png", 16);
            //bar.Items.Add(button);

            // search 
            bar=new RibbonBar();
            bar.Header = "Quick Search";
            panelData.Children.Add(bar);

            StackPanel stackPanel=new StackPanel();
            stackPanel.Margin=new Thickness(5,0,5,0);
            stackPanel.Height = 24;
            stackPanel.Orientation = Orientation.Horizontal;
            Label label=new Label();
            label.Width = 100;
            label.Content = "Entity";
            stackPanel.Children.Add(label);
            ComboBox comboBox=new ComboBox();
            foreach (EntityType entityType in Enum.GetValues(typeof(EntityType)))
                comboBox.Items.Add(entityType.ToString());
            comboBox.SelectionChanged+=new SelectionChangedEventHandler(cboSearchEntityType_SelectionChanged);
            comboBox.Width = 100;
            comboBox.Margin = new Thickness(0);
            comboBox.VerticalAlignment = VerticalAlignment.Center;
            stackPanel.Children.Add(comboBox);
            bar.Items.Add(stackPanel);
            stackPanel=new StackPanel();
            stackPanel.Margin = new Thickness(5, 0, 5, 0);
            stackPanel.Height = 24;
            stackPanel.Orientation = Orientation.Horizontal;
            this.lblSearchField = new Label();
            this.lblSearchField.Width = 100;
            this.lblSearchField.Content = "Field";
            stackPanel.Children.Add(this.lblSearchField);
            this.txtSearch = new TextBox();
            this.txtSearch.Margin = new Thickness(0);
            this.txtSearch.Width = 100;
            this.txtSearch.VerticalAlignment = VerticalAlignment.Center;
            stackPanel.Children.Add(this.txtSearch);
           
            bar.Items.Add(stackPanel);

            button = new ButtonDropDown();
      
            button.Header = "Search";
            button.Image = LoadImage("images/" + EntityIcons.SmallSearchIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(SearchData);
            bar.Items.Add(button);
        }

	    private void cboSearchEntityType_SelectionChanged(object sender, SelectionChangedEventArgs e)
	    {
            if(!this.IsInitialized)
                return;

            if (this.lblSearchField != null)
            {
                ComboBox cbobox = sender as ComboBox;
                if(cbobox==null || cbobox.SelectedIndex <0)
                    return;

                EntityType entityType = (EntityType) Enum.Parse(typeof(EntityType), cbobox.SelectedItem.ToString());
                switch(entityType)
                {
                    case EntityType.Grants:
                        this.lblSearchField.Content = "Project ID:";
                        break;
                    case EntityType.Organizations:
                        this.lblSearchField.Content = "Org name:";
                        break;
                    case EntityType.Persons:
                        this.lblSearchField.Content = "Person name(Last, first):";
                        break;
                    case EntityType.Publications:
                        this.lblSearchField.Content = "PMID:";
                        break;
                }
            }
	    }

	    private void InitRelationRibbonTab(RibbonTab relationTab)
        {
            RibbonBarPanel panelData = new RibbonBarPanel();
            panelData.Height = 89;
            relationTab.Content = panelData;
            RibbonBar bar;
            ButtonDropDown button;

            // from grant -> networks 
            bar = new RibbonBar();
            bar.Header = "Organizations";
            panelData.Children.Add(bar);

            button = new ButtonDropDown();
            button.Header = "Sponsoring orgs";
	        button.ToolTip = "Display grant external orgs who share publications";
            button.Image = LoadImage("/images/wlanpref_210.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(GenerateNetworkForGrantOrgs);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Mesh term orgs";
            button.ToolTip = "Display grant external orgs whoes publication share mesh terms";
            button.Image = LoadImage("/images/networkmap.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(GenerateNetworkForMeshOrgs);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Sponsoring orgs";
            button.ToolTip = "Display publication affiliations who share grants";
            button.Image = LoadImage("/images/" + EntityIcons.GrantLinkIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(GenerateNetworkForSponsoringOrgs);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Org collaborations";
	        button.ToolTip = "Displaying org collaboration via publication citations";
            button.Image = LoadImage("/images/"+EntityIcons.orgLinkIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(GenerateNetworkForOrgCollaborations);
            bar.Items.Add(button);

            // persons 
            bar = new RibbonBar();
            bar.Header = "Persons";
            panelData.Children.Add(bar);

            button = new ButtonDropDown();
            button.Header = "Co-Authors";
            button.ToolTip = "Display authors linked by shared publications in WoS";
            button.Image = LoadImage("/images/import_person.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(GenerateCoAuthorNetworkInWos);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Co-Authors";
            button.ToolTip = "Display authors linked by shared publications in Medline";
            button.Image = LoadImage("/images/import_person.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(GenerateCoAuthorNetworkInMedline);
            bar.Items.Add(button);

            // Docs
            bar = new RibbonBar();
            bar.Header = "Subjects";
            panelData.Children.Add(bar);

            button = new ButtonDropDown();
            button.Header = "Cross disciplines";
	        button.ToolTip = "Display disciplines of published papers";
            button.Image = LoadImage("/images/"+EntityIcons.pubLinkIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(GenerateNetworkForPaperDisciplinaries);
            bar.Items.Add(button);

            // Docs
            bar = new RibbonBar();
            bar.Header = "documents";
            panelData.Children.Add(bar);

            button = new ButtonDropDown();
            button.Header = "Term relations";
            button.ToolTip = "Display ontology tree based on list of related documents";
            button.Image = LoadImage("/images/" + EntityIcons.SplitIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(GenerateTermNetwork);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Doc relations";
            button.ToolTip = "Display clustered docs";
            button.Image = LoadImage("/images/" + EntityIcons.ClusterRuleIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(GenerateDocNetwork);
            bar.Items.Add(button);
        }

        private void InitAnalysisRibbonTab(RibbonTab analysisTab)
        {
            RibbonBarPanel panelData = new RibbonBarPanel();
            panelData.Height = 89;
            analysisTab.Content = panelData;
            RibbonBar bar;
            ButtonDropDown button;

            // filter data 
            bar = new RibbonBar();
            bar.Header = "Select";
            panelData.Children.Add(bar);

            button = new ButtonDropDown();
            button.Header = "Grants";
            button.Image = LoadImage("images/" + EntityIcons.ImportGrantIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(OnSelectGrantHandler);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Organizations";
            button.Image = LoadImage("images/" + EntityIcons.ImportOrgIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(OnSelectOrganizationHandler);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Publications";
            button.Image = LoadImage("images/" + EntityIcons.ImportPubIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(OnSelectPublicationHandler);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Persons";
            button.Image = LoadImage("images/" + EntityIcons.ImportPersonIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(OnSelectPersonHandler);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Save Network";
            button.Image = LoadImage("images/Save32.png", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click += new RoutedEventHandler(OnSaveCurrentNetwork);
            bar.Items.Add(button);

            // filter edges
            bar=new RibbonBar();
            bar.Header = "Filter";
            panelData.Children.Add(bar);

            RadioButton rdDistance=new RadioButton();
            rdDistance.Content = "Distance";
            rdDistance.IsChecked = true;
            bar.Items.Add(rdDistance);
            RadioButton rdHops=new RadioButton();
            rdHops.Content = "Hops";
            rdHops.IsChecked = false;
            RadioButton rdDepth = new RadioButton();
            rdDepth.Content = "Depth";
            rdDepth.IsChecked = false;
            bar.Items.Add(rdDepth);

            // graph 
            bar=new RibbonBar();
            bar.Header = "Graph";
            panelData.Children.Add(bar);

            button=new ButtonDropDown();
            button.Header = "Prestigeous";
            button.ToolTip = "Vertices with highest centrality score";
            button.Image = LoadImage("images/" + EntityIcons.CentralityIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(HighlightPrestigousVertice);
            bar.Items.Add(button);

            button = new ButtonDropDown();
            button.Header = "Popular";
            button.ToolTip = "Vertices with highest degree score";
            button.Image = LoadImage("images/" + EntityIcons.DegreeIcon, 32);
            button.ImagePosition = eButtonImagePosition.Top;
            button.Click +=new RoutedEventHandler(HighlightPopularVertice);
            bar.Items.Add(button);
        }

	    private void OnSaveCurrentNetwork(object sender, RoutedEventArgs e)
	    {
            NetworkGraphView networkGraphView = this.GetActiveNetworkView();
            if (networkGraphView != null)
            {
                Network network = new Network(
                    networkGraphView.NetworkGraph.NetworkName, new List<EntityBase>(), new List<Link>());
                foreach(Vertice v in networkGraphView.NetworkGraph.Graph.Vertices.Values)
                {
                    network.Records.Add(v.Tag);
                }
                foreach(Edge edge in networkGraphView.NetworkGraph.Graph.Edges.Values)
                {
                    network.Links.Add(edge.Tag);
                }
                network.Save();
            }
	    }

	    private void InitReportRibbonTab(RibbonTab reportTab)
        {
            RibbonBarPanel panelData = new RibbonBarPanel();
            panelData.Height = 89;
            reportTab.Content = panelData;
            RibbonBar bar;
            ButtonDropDown button;

            // exports data
            bar = new RibbonBar();
            bar.Header = "Exports";
            panelData.Children.Add(bar);

            button = new ButtonDropDown();
            button.Header = "Export to Excel";
            button.ToolTip = "Export network data, diagram and stats to Excel file";
            button.Image = LoadImage("/images/Excel.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            bar.Items.Add(button);
            button.Click +=new RoutedEventHandler(ExportNetworkToExcel);

            button = new ButtonDropDown();
            button.Header = "Export to Pajek";
            button.ToolTip = "Export network data to Pajek network format";
            button.Image = LoadImage("/images/Pajek.gif", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            bar.Items.Add(button);
            button.Click += new RoutedEventHandler(ExportNetworkToPajek);

            // Affinity
            bar = new RibbonBar();
            bar.Header = "Affinity";
            panelData.Children.Add(bar);

            // Timeline
            bar = new RibbonBar();
            bar.Header = "Time series";
            panelData.Children.Add(bar);

            // Test
            bar = new RibbonBar();
            bar.Header = "Test";
            panelData.Children.Add(bar);

            button = new ButtonDropDown();
            button.Header = "Sample network";
            button.ToolTip = "Create sample network for test";
            button.Image = LoadImage("/images/wdc_108.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            bar.Items.Add(button);
            button.Click += new RoutedEventHandler(CreateTestNetwork);

            button = new ButtonDropDown();
            button.Header = "Performance test";
            button.ToolTip = "Performance profiling using sample network data";
            button.Image = LoadImage("/images/wdc_10024.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            bar.Items.Add(button);
            button.Click += new RoutedEventHandler(TestPerformance);

            // settings 
            bar = new RibbonBar();
            bar.Header = "Settings";
            panelData.Children.Add(bar);
            button = new ButtonDropDown();
            button.Header = "Configuration";
            button.ToolTip = "Edit configuration settings";
            button.Image = LoadImage("/images/import_pub.ico", 32);
            button.ImagePosition = eButtonImagePosition.Top;
            bar.Items.Add(button);
            button.Click += new RoutedEventHandler(OpenConfigFile);

        }

	    private void OpenConfigFile(object sender, RoutedEventArgs e)
	    {
	        string appFilePath = Assembly.GetExecutingAssembly().Location;
	        string configFilePath = appFilePath + ".config";
            if(File.Exists(configFilePath))
            {
                try
                {
                    StreamReader reader=new StreamReader(configFilePath);
                    string content = reader.ReadToEnd();
                    reader.Close();
                    Editor editor=new Editor(content);
                    PopupWindow dialog=new PopupWindow();
                    dialog.Content = editor;
                    editor.ContentChanged += new Editor.OnContentChanged(editor_ContentChanged);
                    dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    dialog.SizeToContent = SizeToContent.WidthAndHeight;
                    dialog.Title = "Configuration Setting";
                    dialog.Show();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Unable to find config file");
            }
	    }

        void editor_ContentChanged(string content)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(content);
                XmlNodeList addNodes = xDoc.DocumentElement.SelectNodes("appSettings/add");
                if(addNodes !=null && addNodes.Count>0)
                {
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    foreach(XmlNode addNode in addNodes)
                    {
                        string key = XmlDataUtil.GetAttributeValue(addNode, "key", "");
                        string val = XmlDataUtil.GetAttributeValue(addNode, "value", "");
                        if (config.AppSettings.Settings[key] != null)
                            config.AppSettings.Settings[key].Value = val;
                        else
                            config.AppSettings.Settings.Add(key, val);

                        if(ConfigurationManager.AppSettings[key]!=null)
                            ConfigurationManager.AppSettings[key] = val;
                        else 
                            ConfigurationManager.AppSettings.Add(key, val);
                    }
                    config.Save();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

	    #endregion

        #region status 
        private void InitStatusBar()
        {
            this.txtUser.Text = Environment.UserName;
        }

        private void HandlesStatusUpdate(string msg, int pct)
        {
            this.txtStatus.Text = msg;
            this.progressBar.Value = pct;
        }
        #endregion

        #region Command Execution
        private eRibbonVisualStyle m_ActiveRibbonColor = eRibbonVisualStyle.Office2007Blue;
		private DevComponents.WpfDock.eDockVisualStyle m_ActiveDockStyle = DevComponents.WpfDock.eDockVisualStyle.Office2007Blue;
		private bool m_CustomColor = false;

		private void MostRecentlyUsedCommandExecute(object sender, ExecutedRoutedEventArgs e)
		{
		}

		private void CloseCommandExecute(object sender, ExecutedRoutedEventArgs e)
		{
			this.Close();
		}

		private void CloseDocumentCommandExecute(object sender, ExecutedRoutedEventArgs e)
		{
		}

		private void AppCommandExecute(object sender, ExecutedRoutedEventArgs e)
		{
			
		}

		private void CanExecuteChangeRibbonColor(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
			IButtonCommandParameter param = e.Parameter as IButtonCommandParameter;
			if (param == null) return;

			if (e.Command == WindowCommands.BlackTheme)
			{
				param.IsChecked = !m_CustomColor && (m_ActiveRibbonColor == eRibbonVisualStyle.Office2007Black);
				param.ValueChanged = true;
			}
			else if (e.Command == WindowCommands.SilverTheme)
			{
				param.IsChecked = !m_CustomColor && (m_ActiveRibbonColor == eRibbonVisualStyle.Office2007Silver);
				param.ValueChanged = true;
			}
			else if (e.Command == WindowCommands.BlueTheme)
			{
				param.IsChecked = !m_CustomColor && (m_ActiveRibbonColor == eRibbonVisualStyle.Office2007Blue);
				param.ValueChanged = true;
			}

		}

		private void ChangeRibbonColor(object sender, ExecutedRoutedEventArgs e)
		{
			ICommand cmd = e.Command;

			//WindowCommands.BlackTheme.IsChecked = (cmd == WindowCommands.BlackTheme);
			//WindowCommands.BlueTheme.IsChecked = (cmd == WindowCommands.BlueTheme);
			//WindowCommands.SilverTheme.IsChecked = (cmd == WindowCommands.SilverTheme);
			//WindowCommands.OrangeTheme.IsChecked = (cmd == WindowCommands.OrangeTheme);
			//WindowCommands.MagentaTheme.IsChecked = (cmd == WindowCommands.MagentaTheme);
			//WindowCommands.GreenTheme.IsChecked = (cmd == WindowCommands.GreenTheme);
			//WindowCommands.DarkBlueTheme.IsChecked = (cmd == WindowCommands.DarkBlueTheme);

			if (cmd == WindowCommands.BlueTheme)
			{
				ChangeColors(eRibbonVisualStyle.Office2007Blue, DevComponents.WpfDock.eDockVisualStyle.Office2007Blue, Colors.Transparent);
			}
			else if (cmd == WindowCommands.SilverTheme)
			{
				ChangeColors(eRibbonVisualStyle.Office2007Silver, DevComponents.WpfDock.eDockVisualStyle.Office2007Silver, Colors.Transparent);
			}
			else if (cmd == WindowCommands.BlackTheme)
			{
				ChangeColors(eRibbonVisualStyle.Office2007Black, DevComponents.WpfDock.eDockVisualStyle.Office2007Black, Colors.Transparent);
			}
			// Custom Colors...
			else if (cmd == WindowCommands.OrangeTheme)
			{
				// Note that you can use any built-in color table as base table any any color as base color
				ChangeColors(eRibbonVisualStyle.Office2007Silver, DevComponents.WpfDock.eDockVisualStyle.Office2007Silver, Color.FromArgb(255, 255, 128, 0));
			}
			else if (cmd == WindowCommands.MagentaTheme)
			{
				ChangeColors(eRibbonVisualStyle.Office2007Silver, DevComponents.WpfDock.eDockVisualStyle.Office2007Silver, Color.FromArgb(255, 215, 23, 204));
			}
			else if (cmd == WindowCommands.GreenTheme)
			{
				ChangeColors(eRibbonVisualStyle.Office2007Silver, DevComponents.WpfDock.eDockVisualStyle.Office2007Silver, Color.FromArgb(255, 0, 149, 4));
			}
			else if (cmd == WindowCommands.DarkBlueTheme)
			{
				ChangeColors(eRibbonVisualStyle.Office2007Silver, DevComponents.WpfDock.eDockVisualStyle.Office2007Silver, Colors.SteelBlue);
			}
		}

		private void ChangeColors(eRibbonVisualStyle ribbonColor, DevComponents.WpfDock.eDockVisualStyle dockColor, Color customBaseColor)
		{
			m_ActiveRibbonColor = ribbonColor;
			m_ActiveDockStyle = dockColor;
			m_CustomColor = (customBaseColor != Colors.Transparent);
			if (m_CustomColor)
			{
				//AppRibbon.ChangeColorScheme(ribbonColor, customBaseColor);
				AppDock.ChangeColorScheme(dockColor, customBaseColor);
			}
			else
			{
				//AppRibbon.ChangeColorScheme(ribbonColor);
				AppDock.ChangeColorScheme(dockColor);
			}
		}
		#endregion

        #region entity set event handlers
        private DockWindow AddNewDocWindow(string header)
        {
            if (!this.tabDocContainer.IsVisible)
            {
                this.tabDocContainer.Visibility = System.Windows.Visibility.Visible;
            }

            DockWindowGroup dockGroup = null;
            if (this.tabDocContainer.Children != null && this.tabDocContainer.Children.Count > 0)
            {
                foreach (var dwg in this.tabDocContainer.Children)
                {
                    if (dwg is DockWindowGroup)
                    {
                        dockGroup = dwg as DockWindowGroup;
                        break;
                    }
                }
            }
            if (dockGroup == null)
            {
                dockGroup = new DockWindowGroup();
                this.tabDocContainer.Children.Add(dockGroup);
            }

            DockWindow newDocWnd = new DockWindow();
            newDocWnd.CanDockBottom = true;
            newDocWnd.CanDockLeft = false;
            newDocWnd.CanDockRight = true;
            newDocWnd.CanDockTop = false;
            newDocWnd.CanFloat = true;
            newDocWnd.Header = header;
            newDocWnd.CloseButtonVisibility = Visibility.Visible;
            dockGroup.Items.Add(newDocWnd);
            newDocWnd.Closing +=new CancelSourceRoutedEventHandler(this.DockWindowClosing);
            return newDocWnd;
        }

        private DockWindow GetActiveDocWindow()
        {
            if (!this.tabDocContainer.IsVisible)
            {
                this.tabDocContainer.Visibility = System.Windows.Visibility.Visible;
            }

            DockWindowGroup dockGroup = null;
            if (this.tabDocContainer.Children != null && this.tabDocContainer.Children.Count > 0)
            {
                foreach (var dwg in this.tabDocContainer.Children)
                {
                    if (dwg is DockWindowGroup)
                    {
                        dockGroup = dwg as DockWindowGroup;
                        break;
                    }
                }
            }
            if (dockGroup == null)
            {
                dockGroup = new DockWindowGroup();
                this.tabDocContainer.Children.Add(dockGroup);
            }
            if(dockGroup.Items !=null && dockGroup.Items.Count>0)
            {
                foreach(var item in dockGroup.Items)
                {
                    if(item is DockWindow)
                    {
                        DockWindow docWindow = (DockWindow) item;
                        if(docWindow.IsSelected)
                            return docWindow;
                    }
                }
            }
            return null;
        }

        private NetworkGraphView GetActiveNetworkView()
        {
            DockWindow docWindow = this.GetActiveDocWindow();
            if(docWindow !=null && docWindow.Content is NetworkGraphView)
            {
                return (NetworkGraphView) (docWindow.Content);
            }
            else
                return null;
        }

        public void HandlesEntitySetEventHandlers(EntityType entityType, string dataSetName)
        {
            DockWindow newDocWnd = this.AddNewDocWindow(dataSetName);
            
            List<EntityBase> entities = DataSetManager.ReadEntitySetData(entityType, dataSetName);
            switch(entityType)
            {
                case EntityType.Grants:
                    GrantListView grantListView=new GrantListView();
                    List<GrantDO> grants=new List<GrantDO>();
                    if(entities !=null && entities.Count>0)
                    {
                        foreach(EntityBase entity in entities)
                        {
                            grants.Add(entity as GrantDO);
                        }
                    }
                    grantListView.Grants = grants;
                    newDocWnd.Content = grantListView;
                    break;
                case EntityType.Organizations:
                    OrgListView orgListView = new OrgListView();
                    List<ExternalOrgDO> orgs = new List<ExternalOrgDO>();
                    if (entities != null && entities.Count > 0)
                    {
                        foreach (EntityBase entity in entities)
                        {
                            orgs.Add(entity as ExternalOrgDO);
                        }
                    }
                    orgListView.Orgs = orgs;
                    newDocWnd.Content = orgListView;
                    break;
                case EntityType.Persons:
                    PersonListView personListView = new PersonListView();
                    List<PersonDO> persons = new List<PersonDO>();
                    if (entities != null && entities.Count > 0)
                    {
                        foreach (EntityBase entity in entities)
                        {
                            persons.Add(entity as PersonDO);
                        }
                    }
                    personListView.Persons = persons;
                    newDocWnd.Content = personListView;
                    break;
                case EntityType.Publications:
                    PubListView pubListView = new PubListView();
                    List<PublicationDO> pubs = new List<PublicationDO>();
                    if (entities != null && entities.Count > 0)
                    {
                        foreach (EntityBase entity in entities)
                        {
                            pubs.Add(entity as PublicationDO);
                        }
                    }
                    pubListView.Pubs = pubs;
                    newDocWnd.Content = pubListView;
                    break;
                case EntityType.Document:
                    DocListView docListView=new DocListView();
                    List<Document> docs=new List<Document>();
                    if(entities !=null && entities.Count>0)
                    {
                        foreach (EntityBase entity in entities)
                        {
                            docs.Add(entity as Document);
                        }
                    }
                    docListView.Docs = docs;
                    newDocWnd.Content = docListView;
                    break;
            }

            newDocWnd.IsSelected = true;
            AppSettings.CurrentActiveWindow = newDocWnd;
            AppSettings.CurrentObject = entities;
        }
        #endregion

        #region network event handlers
        public void OnViewNetworkGraph(Network network)
        {
            DockWindow newDocWnd = this.AddNewDocWindow(network.NetworkName);
            NetworkGraphView networkGraphView = new NetworkGraphView();
            networkGraphView.StatusChanged +=new NetworkGraphView.OnStatusChanged(HandlesStatusUpdate);
            newDocWnd.Content = networkGraphView;
            newDocWnd.IsSelected = true;
            networkGraphView.OnViewNetwork(network);
            AppSettings.CurrentActiveWindow = newDocWnd;
            AppSettings.CurrentObject = network;
        }

	    public void OnViewNetworkStats(Network network)
        {
            DockWindow newDocWnd = this.AddNewDocWindow(network.NetworkName);
            NetworkStats networkStatsView = new NetworkStats();
            newDocWnd.Content = networkStatsView;
            newDocWnd.IsSelected = true;
            networkStatsView.PopulateNetworkStats(network);

            AppSettings.CurrentActiveWindow = newDocWnd;
            AppSettings.CurrentObject = network;
        }

        public void OnViewNetworkData(Network network)
        {
            DockWindow newDocWnd = this.AddNewDocWindow(network.NetworkName);
            NetworkData networkDataView = new NetworkData();
            networkDataView.EntitiesSelected += new NetworkData.OnEntitiesSelected(networkDataView_EntitiesSelected);
            newDocWnd.Content = networkDataView;
            newDocWnd.IsSelected = true;
            networkDataView.PopulateNetworkEntities(network);
            AppSettings.CurrentActiveWindow = newDocWnd;
            AppSettings.CurrentObject = network;
        }

        void networkDataView_EntitiesSelected(List<EntityBase> entities)
        {
            NetworkGraphView networkGraphView = this.GetActiveNetworkView();
            if (networkGraphView != null && !string.IsNullOrEmpty(networkGraphView.NetworkGraph.NetworkName))
            {
                networkGraphView.SelectEntities(entities);
            }
        }
        #endregion

        #region dock window event handlers
        private void DialogLauncherClicked(object sender, RoutedEventArgs e)
		{
		}

		private void DockWindowActivated(object sender, RoutedEventArgs e)
		{
		    
		}

		private void DockWindowClosing(object sender, CancelSourceRoutedEventArgs e)
		{
			if(sender is DockWindow)
			{
			    DockWindow dcWind = (DockWindow) sender;
                if(dcWind.Content is NetworkGraphView)
                {
                    NetworkGraphView networkGraphView = (NetworkGraphView)dcWind.Content;
                    networkGraphView.Dispose();
                }
			}
		}

		private void DockWindowDeactivated(object sender, RoutedEventArgs e)
		{
			
		}

		private void DockWindowClosed(object sender, RoutedEventArgs e)
		{
			
		}

        private void ShowWizard()
        {
            List<IWizardPageBase> wizPages = new List<IWizardPageBase>();
            PageRuleEditorIntro pageIntro = new PageRuleEditorIntro();
            PageRuleEditorSrcFields pageSrcFields = new PageRuleEditorSrcFields();
            pageIntro.PrevPage = null;
            pageIntro.NextPage = pageSrcFields;
            pageIntro.Title = "Welcome";
            pageIntro.Description = "";
            pageSrcFields.PrevPage = pageIntro;
            pageSrcFields.NextPage = null;
            pageSrcFields.Title = "Source fields";
            pageSrcFields.Description = string.Empty;
            wizPages.Add(pageIntro);
            wizPages.Add(pageSrcFields);
            Wizard wiz = new Wizard(null, wizPages.ToArray(), pageIntro);
            wiz.Owner = this;
            wiz.Show();
        }
        #endregion

        #region commands
        private void NewCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

	    private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
	    {
	        e.CanExecute = false;
	    }

	    private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e)
	    {
            
            ImportRuleEditor importer=new ImportRuleEditor();
            importer.Cancel += new ImportRuleEditor.OnCancel(importer_Cancel);
            importer.ImportRuleDefined += new ImportRuleEditor.OnImportRuleDefined(importer_ImportRuleDefined);
            PopupWindow dialog=new PopupWindow();
	        dialog.Content = importer;
	        dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
	        dialog.Show();
	    }

        void importer_ImportRuleDefined(DiscoveryLogic.Analytics.DataObjects.Rules.EntityImportRule rule)
        {
            RuleManager.Save(rule);
            string dataSetName = System.IO.Path.GetFileNameWithoutExtension(rule.DataSourcePath);
            ImportRuleWorker worker=new ImportRuleWorker(rule, rule.DataSourcePath, dataSetName);
            List<EntityBase> entities = worker.RetrieveEntities();
            string iconPath = string.Empty;
            switch(rule.TgtEntityType)
            {
                case EntityType.Grants:
                    iconPath = "../images/tools.png";
                    break;
                case EntityType.Organizations:
                    iconPath = "../images/home.png";
                    break;
                case EntityType.Persons:
                    iconPath = "../images/user.png";
                    break;
                case EntityType.Publications:
                    iconPath = "../images/doc.png";
                    break;
            }
            EntityDataSet entityDataSet =
                new EntityDataSet(dataSetName, iconPath, rule.TgtEntityType,
                                  SetDataSourceType.ExcelFile, entities);
            entityDataSet.Save();


            MyData.ReadAllRules();
            MyData.ReadAllEntitySets();
        }

        void importer_Cancel()
        {
            this.popup.IsOpen = false;
        }

	    private void SaveCommane_Executed(object sender, ExecutedRoutedEventArgs e)
	    {

        }
        
	    private void btnSearch_Click(object sender, RoutedEventArgs e)
	    {
            PopupWindow dialog=new PopupWindow();
            QuickSearch searcher = new QuickSearch(dialog);
	        dialog.Content = searcher;
            //this.popup.Placement = PlacementMode.Center;
            //this.popupContainer.Content = searcher;
            //this.popup.StaysOpen = true;
            //this.popup.IsOpen = true; 
	        dialog.SizeToContent = SizeToContent.WidthAndHeight;
            dialog.Title = "Search";
            dialog.Show();
        }

        #endregion

        #region data command
        private void ImportExcelData(object sender, RoutedEventArgs e)
        {
            ImportCustomData importCustomData=new ImportCustomData();
            PopupWindow dialog=new PopupWindow();
            dialog.Content = importCustomData;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.SizeToContent = SizeToContent.WidthAndHeight;
            dialog.Title = "Import data";
            dialog.Show();
        }

        private void ImportData(object sender, RoutedEventArgs e)
        {
            ButtonDropDown btn = sender as ButtonDropDown;
            if(btn.Header.ToString()=="Grants")
                this.ImportData(EntityType.Grants);
            else if (btn.Header.ToString() == "Organizations")
                this.ImportData(EntityType.Organizations);
            else if (btn.Header.ToString() == "Publications")
                this.ImportData(EntityType.Publications);
            else if (btn.Header.ToString() == "Persons")
                this.ImportData(EntityType.Persons);
        }

        private void ImportData(EntityType entityType)
        {
            PopupWindow dialog = new PopupWindow();
            switch(entityType)
            {
                case EntityType.Grants:
                    GrantImporter grantImporter=new GrantImporter();
                    grantImporter.DataImported+=new GrantImporter.OnDataImported(HandlesDataImported);
                    grantImporter.StatusChanged +=new GrantImporter.OnStatusChanged(HandlesStatusUpdate);
                    dialog.Content = grantImporter;
                    break;
                case EntityType.Publications:
                    PubImporter pubImporter=new PubImporter();
                    pubImporter.DataImported +=new PubImporter.OnDataImported(HandlesDataImported);
                    pubImporter.StatusChanged +=new PubImporter.OnStatusChanged(HandlesStatusUpdate);
                    dialog.Content = pubImporter;
                    break;
                default:
                    DataImportEditor editor = new DataImportEditor();
                    editor.EntityDataSetCreated += new DataImportEditor.OnEntityDataSetCreated(editor_EntityDataSetCreated);
                    dialog.Content = editor;
                    break;
            }
            
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.SizeToContent = SizeToContent.WidthAndHeight;
            dialog.Title = "Import data";
            dialog.Show();
        }

	    private void HandlesDataImported(string networkName)
	    {
	        MyData.ReadAllNetworks();
	        Network network = Network.Read(networkName);
            this.OnViewNetworkGraph(network);
	    }

	    void editor_EntityDataSetCreated(EntityDataSet entitySet)
        {
            entitySet.Save();
            MyData.ReadAllEntitySets();
        }

        private void SearchData(object sender, RoutedEventArgs e)
        {
            if(this.lblSearchField ==null || this.txtSearch==null)
                return;
            EntityType searchEntity = EntityType.Grants;
            string searchField = "ProjectID";
            string searchText = this.txtSearch.Text;
            if (this.lblSearchField.Content=="Project ID:")
            {
                searchEntity = EntityType.Grants;
                searchField = "ProjectID";
            }
            else if(this.lblSearchField.Content=="Org name:")
            {
                searchEntity = EntityType.Organizations;
                searchField = "OrgName";
            }
            else if(this.lblSearchField.Content.ToString().StartsWith("Person name"))
            {
                searchEntity = EntityType.Persons;
                searchField = "FullName";
            }
            else if(this.lblSearchField.Content=="PMID:")
            {
                searchEntity = EntityType.Publications;
                searchField = "PMID";
            }
            this.SearchData(searchEntity, searchField, searchText);
        }

        private void SearchData(EntityType entityType, string fieldName, string searchText)
        {
            PopupWindow dialog = new PopupWindow();
            QuickSearch searcher = new QuickSearch(dialog);
            dialog.Content = searcher;
            //this.popup.Placement = PlacementMode.Center;
            //this.popupContainer.Content = searcher;
            //this.popup.StaysOpen = true;
            //this.popup.IsOpen = true; 
            dialog.SizeToContent = SizeToContent.WidthAndHeight;
            dialog.Title = "Search";
            dialog.Show();
        }
        #endregion

        #region relations commands
        private void GenerateNetworkForGrantOrgs(object sender, RoutedEventArgs e)
        {
            PopupWindow dialog = new PopupWindow();
            GrantOrgNetwork networkCreator = new GrantOrgNetwork();
            networkCreator.NetworkCreated += new GrantOrgNetwork.OnNetworkCreated(HandlesNetworkCreated);
            networkCreator.StatusChanged += new GrantOrgNetwork.OnStatusChanged(HandlesStatusUpdate);
            dialog.Content = networkCreator;
            dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.Title = "Sponsor network";
            dialog.Show();
        }

        private void GenerateNetworkForMeshOrgs(object sender, RoutedEventArgs e)
        {
            PopupWindow dialog = new PopupWindow();
            SponsoringOrgsViaMeshTerms networkCreator = new SponsoringOrgsViaMeshTerms();
            networkCreator.NetworkCreated += new SponsoringOrgsViaMeshTerms.OnNetworkCreated(HandlesNetworkCreated);
            networkCreator.StatusChanged += new SponsoringOrgsViaMeshTerms.OnStatusChanged(HandlesStatusUpdate);
            dialog.Content = networkCreator;
            dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.Title = "Mesh term network";
            dialog.Show();
        }

        private void GenerateNetworkForSponsoringOrgs(object sender, RoutedEventArgs e)
        {
            PopupWindow dialog=new PopupWindow();
            SponsoringOrgNetwork networkCreator=new SponsoringOrgNetwork();
            networkCreator.NetworkCreated+=new SponsoringOrgNetwork.OnNetworkCreated(HandlesNetworkCreated);
            networkCreator.StatusChanged +=new SponsoringOrgNetwork.OnStatusChanged(HandlesStatusUpdate);
            dialog.Content = networkCreator;
            dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.Title = "Sponsor network";
            dialog.Show();
        }

	    private void HandlesNetworkCreated(Network network)
	    {
	        this.HandlesStatusUpdate("Reading networks...", 50);
            MyData.ReadAllNetworks();
            this.HandlesStatusUpdate("Displaying networks...", 90);
            this.OnViewNetworkGraph(network);
	        this.HandlesStatusUpdate("", 0);
	    }

	    private void GenerateNetworkForOrgCollaborations(object sender, RoutedEventArgs e)
        {
            PopupWindow dialog = new PopupWindow();
            CollapratingOrgNetwork networkCreator = new CollapratingOrgNetwork();
            networkCreator.NetworkCreated +=new CollapratingOrgNetwork.OnNetworkCreated(HandlesNetworkCreated);
            networkCreator.StatusChanged += new CollapratingOrgNetwork.OnStatusChanged(HandlesStatusUpdate);
            dialog.Content = networkCreator;
            dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.Title = "Collaboration network";
            dialog.Show();
        }

        private void GenerateCoAuthorNetworkInWos(object sender, RoutedEventArgs e)
        {
            PopupWindow dialog = new PopupWindow();
            CoAuthorNetwork networkCreator = new CoAuthorNetwork();
            networkCreator.NetworkCreated += new CoAuthorNetwork.OnNetworkCreated(HandlesNetworkCreated);
            networkCreator.StatusChanged += new CoAuthorNetwork.OnStatusChanged(HandlesStatusUpdate);
            dialog.Content = networkCreator;
            dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.Title = "Co-author network";
            dialog.Show();
        }

        private void GenerateCoAuthorNetworkInMedline(object sender, RoutedEventArgs e)
        {
            PopupWindow dialog = new PopupWindow();
            CoAuthorNetworkInMedline networkCreator = new CoAuthorNetworkInMedline();
            networkCreator.NetworkCreated += new CoAuthorNetworkInMedline.OnNetworkCreated(HandlesNetworkCreated);
            networkCreator.StatusChanged += new CoAuthorNetworkInMedline.OnStatusChanged(HandlesStatusUpdate);
            dialog.Content = networkCreator;
            dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.Title = "Co-author network";
            dialog.Show();
        }

        private void GenerateNetworkForPaperDisciplinaries(object sender, RoutedEventArgs e)
        {
            PopupWindow dialog = new PopupWindow();
            CrossDisciplinaryNetwork networkCreator = new CrossDisciplinaryNetwork();
            networkCreator.NetworkCreated +=new CrossDisciplinaryNetwork.OnNetworkCreated(HandlesNetworkCreated);
            networkCreator.StatusChanged +=new CrossDisciplinaryNetwork.OnStatusChanged(HandlesStatusUpdate);
            dialog.Content = networkCreator;
            dialog.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.Title = "Disciplinary network";
            dialog.Show();
        }

        private void GenerateTermNetwork(object sender, RoutedEventArgs e)
        {
            
        }

        private void GenerateDocNetwork(object sender, RoutedEventArgs e)
        {
            
        }

        private void DefineLinkRule(EntityType fromEntity, EntityType toEntity)
        {
            
        }

        private void OpenLinkRule(string ruleName)
        {
            
        }
        #endregion

        #region analysis commands
        void OnSelectGrantHandler(object sender, RoutedEventArgs e)
        {
            this.SelectEntityType(EntityType.Grants);
        }

        void OnSelectPublicationHandler(object sender, RoutedEventArgs e)
        {
            this.SelectEntityType(EntityType.Publications);
        }

        void OnSelectOrganizationHandler(object sender, RoutedEventArgs e)
        {
            this.SelectEntityType(EntityType.Organizations);
        }

        void OnSelectPersonHandler(object sender, RoutedEventArgs e)
        {
            this.SelectEntityType(EntityType.Persons);
        }

        private void SelectEntityType(EntityType entityType)
        {
            NetworkGraphView networkGraphView = this.GetActiveNetworkView();
            if(networkGraphView !=null)
            {
                networkGraphView.SelectEntities(entityType);
            }
        }

        private void ChangeDistanceSliderType(bool useHops)
        {
            
        }

        private void HighlightPrestigousVertice(object sender, RoutedEventArgs e)
        {
            NetworkGraphView networkGraphView = this.GetActiveNetworkView();
            if (networkGraphView != null)
            {
                networkGraphView.HighlightPrestigiousEntities();
            }
        }

        private void HighlightPopularVertice(object sender, RoutedEventArgs e)
        {
            NetworkGraphView networkGraphView = this.GetActiveNetworkView();
            if (networkGraphView != null)
            {
                networkGraphView.HighlightPopularEntities();
            }
        }
        #endregion

        #region report command handler
        private void ExportNetworkToExcel(object sender, RoutedEventArgs e)
        {
            Network network = null;
            NetworkGraphView networkGraphView = this.GetActiveNetworkView();
            if (networkGraphView != null && !string.IsNullOrEmpty(networkGraphView.NetworkGraph.NetworkName))
            {
                network = Network.Read(networkGraphView.NetworkGraph.NetworkName);
            }
            else if (AppSettings.CurrentObject != null && AppSettings.CurrentObject is Network)
            {
                network = (Network)AppSettings.CurrentObject;
            }

            if(network==null)
            {
                MessageBox.Show("Open or select network graph before export");
            }
            else
            {
                string excelFolder = System.IO.Path.Combine(DataFolder.NetworkDataFolder, "Excel");
                if (!Directory.Exists(excelFolder))
                    Directory.CreateDirectory(excelFolder);
                string excelFilePath = System.IO.Path.Combine(excelFolder, network.NetworkName + ".xlsx");
                ExcelReportUtil.ExportToExcel(network, excelFilePath);
                MessageBox.Show("Network saved to " + excelFilePath);
            }
        }

        /// <summary>
        /// G1,G2,G3->P1,P2,P3->P101-303->Org1-303
        /// </summary>
        /// <param name="networkName"></param>
        private Network GenerateTestNetwork(string networkName)
        {
            Network testNet = new Network(networkName, new List<EntityBase>(), new List<Link>());
            GrantDO grant = new GrantDO();
            int id = 0;
            grant.ProjectID = id++;
            grant.GrantNumber = "Grant 1";
            testNet.Records.Add(grant);

            for (int i = 1; i <= 3; i++)
            {
                PublicationDO pub = new PublicationDO();
                pub.PMID = id++;
                pub.Title = "Pub " + i.ToString();
                testNet.Records.Add(pub);
                Link link = new Link(
                    typeof(GrantDO), typeof(PublicationDO), 
                    grant.PKValue(), pub.PKValue(), 1, 1, 
                    LinkType.Citation, true);
                testNet.Links.Add(link);

                for (int k = 1; k <= 10; k++)
                {
                    PublicationDO pub2 = new PublicationDO();
                    pub2.PMID = id++;
                    pub2.Title = string.Format("Pub {0}-{1}", i, k);
                    testNet.Records.Add(pub2);

                    Link link2 = new Link(
                        typeof(PublicationDO), typeof(PublicationDO),
                        pub.PKValue(), pub2.PKValue(), 1,1,
                        LinkType.Citation, true);
                    testNet.Links.Add(link2);

                    ExternalOrgDO org = new ExternalOrgDO();
                    org.ExternalOrgID = id++;
                    org.OrgName = string.Format("Org {0}-{1}", i, k);
                    testNet.Records.Add(org);
                    Link link3 = new Link(
                        typeof(PublicationDO), typeof(ExternalOrgDO),
                        pub2.PKValue(), org.PKValue(), 2, 1, LinkType.Citation, false);
                    testNet.Links.Add(link3);
                }
            }

            testNet.Save();
            MyData.ReadAllNetworks();

            return testNet;
        }

        private void ExportNetworkToPajek(object sender, RoutedEventArgs e)
        {
            if(AppSettings.CurrentObject !=null && AppSettings.CurrentObject is Network)
            {
                Network network = (Network) AppSettings.CurrentObject;
                string pajekFolder = System.IO.Path.Combine(DataFolder.NetworkDataFolder, "Pajek");
                if (!Directory.Exists(pajekFolder))
                    Directory.CreateDirectory(pajekFolder);
                string pajekFilePath = System.IO.Path.Combine(pajekFolder, network.NetworkName + ".net");
                PajekExportUtil.ExportNetworkToPajek(network, pajekFilePath);
                MessageBox.Show("Network saved to " + pajekFilePath);
            }
        }

        private void CreateTestNetwork(object sender, RoutedEventArgs e)
        {
            this.GenerateTestNetwork("Test");
        }

        private void TestPerformance(object sender, RoutedEventArgs e)
        {
            Network testNet = this.GenerateTestNetwork("Test");
            NetworkFuzzyClusterWorker clusterWorker=new NetworkFuzzyClusterWorker(testNet);
            Dictionary<int,List<EntityBase>> groupedEntities = clusterWorker.ExclusivelyClusterNetwork();
            string fileName = "test.cluster";
            if(File.Exists(fileName))
                File.Delete(fileName);
            StreamWriter writer = new StreamWriter(fileName);
            foreach(int groupID in groupedEntities.Keys)
            {
                writer.WriteLine("Group {0}", groupID);
                foreach(EntityBase entity in groupedEntities[groupID])
                {
                    writer.WriteLine("{0} {1}", entity.EntityType.ToString(), entity.Name);
                }
            }
            writer.Flush();
            writer.Close();
        }
        #endregion
    }
}
